import random
from playcard import make_deck, is_red, get_rank, RANK_MAP, SUITS

# Return two integers a<b in range(n), assuming n>=2
def rand_int_pair(n):
    a = random.randint(0,n-1)
    b = (a + random.randint(1, n-1))%n
    return (a,b) if a<b else (b,a)

def new_game(session):
    # Create a standard deck of 52 cards
    deck = make_deck()
    random.shuffle(deck)
    tableau = [[] for _ in range(8)]
    for i, card in enumerate(deck):
        tableau[i % 8].append(card)

    # make the deal easier because it is often difficult
    for i in range(8):
        column = tableau[i]
        n = 7 if i<4 else 6
        for _ in range(random.randint(2,3)):
            a, b = rand_int_pair(n)
            if get_rank(column[a]) < get_rank(column[b]):
                column[a], column[b] = column[b], column[a]

    session['game_state'] = {
        'cells': [[] for _ in range(4)],
        'piles': [[] for _ in range(4)],
        'tableau': tableau,
        'game_over': False,
        'message': '',
    }
    return


# Return (is_red, rank) for a card
def color_and_rank(card):
    return is_red(card), get_rank(card)

# Convert string to int, return -1 if conversion fails
def safe_int(digit):
    try:
        return int(digit)
    except ValueError:
        return -1



def game_update(session, action):
    game_state = session.get('game_state', {})
    if not game_state:
        return new_game(session)

    # TODO: Students to implement game logic based on action
    # - 'tt<source><target>': Move card(s) from column <source> to column <target> (0-based)
    # - 'tc<source><target>': Move card from column <source> to cell <target> (0-based)
    # - 'ct<source><target>': Move card from cell <source> to column <target> (0-based)
    # - 'tf<column>': Move last card from column <column> (0-based) to foundation
    # - 'cf<cell>': Move card from cell <cell> (0-based) to foundation
    if action.startswith('tt') and len(action) == 4:
        ...

    elif action.startswith('tc') and len(action) == 4:
        ...

    elif action.startswith('ct') and len(action) == 4:
        ...

    elif action.startswith('tf') and len(action) == 3:
        ...

    elif action.startswith('cf') and len(action) == 3:
        ...

    else:
        ...

    # game state has changed itself so tell session it has changed
    session.modified = True
    return

